<!--kdkadjka-->
<template>
  <el-container>
    <el-header>
      <h2>优惠券中心</h2>
    </el-header>
    <el-main>
      <el-input v-model="exchangeCode" placeholder="请输入兑换码" style="width: 300px; margin-bottom: 10px;"></el-input>
      <el-button type="primary" @click="handleExchange">兑换优惠券</el-button>
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="未使用的优惠券" name="unused">
          <el-table :data="unusedCoupons" stripe>
            <el-table-column prop="name" label="优惠券名称" width="180"></el-table-column>
            <el-table-column prop="discount_type" label="优惠类型" width="120">
              <template #default="scope">
                <span>{{ getDiscountType(scope.row.discount_type) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="discount_value" label="折扣值" width="150">
              <template #default="scope">
                <span>{{ formatDiscountValue(scope.row) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="threshold_amount" label="满减门槛" width="150">
              <template #default="scope">
                <span>{{ scope.row.threshold_amount > 0 ? (scope.row.threshold_amount) + ' 元' : '无门槛' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="total_num" label="总数量" width="100">
              <template #default="scope">
                <span>{{ scope.row.total_num }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="user_limit" label="用户限领数量" width="180">
              <template #default="scope">
                <span>{{ scope.row.user_limit }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="已使用的优惠券" name="used">
          <el-table :data="usedCoupons" stripe>
            <el-table-column prop="name" label="优惠券名称" width="180"></el-table-column>
            <el-table-column prop="discount_type" label="优惠类型" width="120">
              <template #default="scope">
                <span>{{ getDiscountType(scope.row.discount_type) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="discount_value" label="折扣值" width="150">
              <template #default="scope">
                <span>{{ formatDiscountValue(scope.row) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="threshold_amount" label="满减门槛" width="150">
              <template #default="scope">
                <span>{{ scope.row.threshold_amount > 0 ? (scope.row.threshold_amount) + ' 元' : '无门槛' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="total_num" label="总数量" width="100">
              <template #default="scope">
                <span>{{ scope.row.total_num }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="user_limit" label="用户限领数量" width="180">
              <template #default="scope">
                <span>{{ scope.row.user_limit }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-main>
  </el-container>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {getYhUserByStatus, getCouponsByCouponId, selectCode, addYhUser} from '@/api/coupon.js';

const activeTab = ref('unused');
const unusedCoupons = ref([]);
const usedCoupons = ref([]);
const exchangeCode = ref('');

// 获取用户ID
const userInfoString = localStorage.getItem('userInfo');
const user = ref(JSON.parse(userInfoString));
const userId = user.value.id;

const fetchCoupons = async () => {
  try {
    // 获取未使用的优惠券
    const { data: unusedData } = await getYhUserByStatus(1);
    // 获取已使用的优惠券
    const { data: usedData } = await getYhUserByStatus(2);

    // 获取未使用和已使用优惠券的详细信息
    const unusedCouponIds = unusedData.filter(item => item.user_id === userId).map(item => item.coupon_id);
    const usedCouponIds = usedData.filter(item => item.user_id === userId).map(item => item.coupon_id);

    // 获取未使用优惠券的详细信息
    const unusedCouponsData = await Promise.all(unusedCouponIds.map(id => getCouponsByCouponId(id)));
    unusedCoupons.value = unusedCouponsData.flatMap(res => res.data); // 扁平化数据

    // 获取已使用优惠券的详细信息
    const usedCouponsData = await Promise.all(usedCouponIds.map(id => getCouponsByCouponId(id)));
    usedCoupons.value = usedCouponsData.flatMap(res => res.data); // 扁平化数据
  } catch (error) {
    console.error('获取优惠券信息失败:', error);
  }
};


const getDiscountType = (type) => {
  switch (type) {
    case 1:
      return '每满减';
    case 2:
      return '折扣';
    case 3:
      return '无门槛';
    default:
      return '未知';
  }
};

const formatDiscountValue = (coupon) => {
  if (coupon.discount_type === 1) {
    return `${coupon.discount_value} 元`;
  } else if (coupon.discount_type === 2) {
    return `${coupon.discount_value / 10} 折`;
  } else if (coupon.discount_type === 3) {
    return `${coupon.discount_value} 元`;   //改了这里，原来是"无门槛"
  } else {
    return '未知';
  }
};

const handleExchange = async () => {
  try {
    // 调用 selectCode 接口检查兑换码
    const {data: yhCodeData} = await selectCode(exchangeCode.value);
    if (yhCodeData.status === 1) {
      // 兑换码可用，获取 coupon_id
      const yhUser = {
        user_id: userId,
        coupon_id: yhCodeData.coupon_id,
        status: 1
      };
      // 调用 addYhUser 接口兑换优惠券
      const result = await addYhUser(yhUser);
      console.log("result:",result)
      if (result.code === 1) {
        alert('兑换成功');
        fetchCoupons(); // 重新获取优惠券列表
      } else {
        alert('兑换失败：' + result.msg);
      }
    } else {
      alert('兑换码已被使用');
    }
  } catch (error) {
    console.error('兑换优惠券失败:', error);
    alert('兑换失败，请重试');
  }
};

onMounted(() => {
  fetchCoupons();
});
</script>

<style scoped>
.el-header {
  background-color: #f5f5f5;
  padding: 10px;
  text-align: center;
}

h2 {
  margin: 0;
}

.el-tabs {
  margin-top: 10px;
}
</style>
